<template>
  <div class="user-list">
    <!-- 消息提示 -->
    <div v-if="message.show" :class="['message-toast', message.type]" @click="clearMessage">
      <div class="message-content">
        <i :class="['message-icon', message.type === 'success' ? '✓' : '✗']"></i>
        <span class="message-text">{{ message.text }}</span>
        <button class="message-close" @click="clearMessage">×</button>
      </div>
    </div>
    
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统用户信息</p>
    </div>
    
    <div class="content-section">
      <div class="action-bar">
        <div class="left-actions">
          <button class="btn btn-primary" @click="showAddUserModal">
            <i class="icon">➕</i>
            新增用户
          </button>
          <button class="btn btn-secondary" @click="refreshUsers">
          <span class="icon">↻</span>
          刷新
        </button>
        </div>
        <div class="filter-group">
          <select v-model="genderFilter" class="filter-select">
            <option value="">全部性别</option>
            <option value="1">男</option>
            <option value="2">女</option>
            <option value="0">未知</option>
          </select>
          <select v-model="statusFilter" class="filter-select">
            <option value="">全部状态</option>
            <option value="1">正常</option>
            <option value="0">已禁用</option>
          </select>
        </div>
        <div class="search-box">
          <input type="text" placeholder="搜索用户名、昵称或邮箱..." v-model="searchQuery">
          <i class="search-icon">🔍</i>
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载用户数据...</p>
      </div>
      
      <div v-else-if="error" class="error-message">
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="fetchUsers">重新加载</button>
      </div>
      
      <div v-else class="users-table">
        <table class="user-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>昵称</th>
              <th>邮箱</th>
              <th>手机号</th>
              <th>性别</th>
              <th>状态</th>
              <th>最后登录</th>
              <th>注册时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.id" :class="{ 'disabled-row': user.status === 0 }">
              <td class="user-id">{{ user.id }}</td>
              <td class="username">{{ user.username }}</td>
              <td class="nickname">{{ user.nickname || '-' }}</td>
              <td>{{ user.email || '-' }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>
                <span :class="['gender', getGenderClass(user.gender)]">
                  {{ getGenderText(user.gender) }}
                </span>
              </td>
              <td>
                <span :class="['status', user.status === 0 ? 'disabled' : 'active']">
                  {{ user.status === 0 ? '已禁用' : '正常' }}
                </span>
              </td>
              <td>{{ formatDate(user.last_login_at) }}</td>
              <td>{{ formatDate(user.created_at) }}</td>
              <td class="actions">
                <button class="btn-edit" @click="editUser(user)" :disabled="user.status === 0">编辑</button>
                <button class="btn-view" @click="viewUserDetail(user)">详情</button>
                <button 
                  :class="['btn-toggle', user.status === 0 ? 'btn-enable' : 'btn-disable']" 
                  @click="toggleUserStatus(user)"
                  :disabled="toggleLoading === user.id"
                >
                  {{ toggleLoading === user.id ? '处理中...' : (user.status === 0 ? '启用' : '禁用') }}
                </button>
                <button class="btn-delete" @click="deleteUser(user)" :disabled="user.status === 0">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div v-if="filteredUsers.length === 0" class="no-data">
          <p>暂无用户数据</p>
        </div>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="pagination.total > 0" class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ pagination.total }} 条记录，第 {{ pagination.pageNum }} / {{ pagination.pages }} 页</span>
          <div class="page-size-selector">
            <label>每页显示：</label>
            <select v-model="pagination.pageSize" @change="changePageSize(pagination.pageSize)">
              <option value="5">5条</option>
              <option value="10">10条</option>
              <option value="20">20条</option>
              <option value="50">50条</option>
            </select>
          </div>
        </div>
        
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            @click="goToFirstPage" 
            :disabled="pagination.isFirstPage"
            title="首页"
          >
            ⟪
          </button>
          <button 
            class="page-btn" 
            @click="goToPreviousPage" 
            :disabled="!pagination.hasPreviousPage"
            title="上一页"
          >
            ⟨
          </button>
          
          <div class="page-numbers">
            <button 
              v-for="pageNum in getPageNumbers()" 
              :key="pageNum"
              class="page-btn"
              :class="{ active: pageNum === pagination.pageNum }"
              @click="changePage(pageNum)"
              :disabled="pageNum === '...'"
            >
              {{ pageNum }}
            </button>
          </div>
          
          <button 
            class="page-btn" 
            @click="goToNextPage" 
            :disabled="!pagination.hasNextPage"
            title="下一页"
          >
            ⟩
          </button>
          <button 
            class="page-btn" 
            @click="goToLastPage" 
            :disabled="pagination.isLastPage"
            title="末页"
          >
            ⟫
          </button>
        </div>
      </div>
    </div>

    <!-- 用户添加/编辑模态框 -->
    <div v-if="showUserModal" class="modal-overlay" @click="closeUserModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditMode ? '编辑用户' : '新增用户' }}</h3>
          <button class="close-btn" @click="closeUserModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-row">
              <div class="form-group">
                <label>用户名 *</label>
                <input 
                  type="text" 
                  v-model="userForm.username" 
                  :disabled="isEditMode"
                  required 
                  placeholder="请输入用户名"
                >
              </div>
              <div class="form-group">
                <label>昵称</label>
                <input 
                  type="text" 
                  v-model="userForm.nickname" 
                  placeholder="请输入昵称"
                >
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>邮箱</label>
                <input 
                  type="email" 
                  v-model="userForm.email" 
                  placeholder="请输入邮箱"
                >
              </div>
              <div class="form-group">
                <label>手机号</label>
                <input 
                  type="tel" 
                  v-model="userForm.phone" 
                  placeholder="请输入手机号"
                >
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>性别</label>
                <select v-model="userForm.gender">
                  <option value="0">未知</option>
                  <option value="1">男</option>
                  <option value="2">女</option>
                </select>
              </div>
              <div class="form-group">
                <label>状态</label>
                <select v-model="userForm.status">
                  <option value="1">正常</option>
                  <option value="0">禁用</option>
                </select>
              </div>
            </div>
            <div class="form-row" v-if="!isEditMode">
              <div class="form-group">
                <label>密码 *</label>
                <input 
                  type="password" 
                  v-model="userForm.password" 
                  required 
                  placeholder="请输入密码"
                >
              </div>
              <div class="form-group">
                <label>确认密码 *</label>
                <input 
                  type="password" 
                  v-model="userForm.confirmPassword" 
                  required 
                  placeholder="请再次输入密码"
                >
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeUserModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="saving">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 用户详情查看模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>用户详情</h3>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-info" v-if="selectedUser">
            <div class="detail-row">
              <label>用户ID:</label>
              <span>{{ selectedUser.id }}</span>
            </div>
            <div class="detail-row">
              <label>用户名:</label>
              <span>{{ selectedUser.username }}</span>
            </div>
            <div class="detail-row">
              <label>昵称:</label>
              <span>{{ selectedUser.nickname || '-' }}</span>
            </div>
            <div class="detail-row">
              <label>邮箱:</label>
              <span>{{ selectedUser.email || '-' }}</span>
            </div>
            <div class="detail-row">
              <label>手机号:</label>
              <span>{{ selectedUser.phone || '-' }}</span>
            </div>
            <div class="detail-row">
              <label>性别:</label>
              <span>{{ getGenderText(selectedUser.gender) }}</span>
            </div>
            <div class="detail-row">
              <label>状态:</label>
              <span :class="['status', selectedUser.status === 0 ? 'disabled' : 'active']">
                {{ selectedUser.status === 0 ? '已禁用' : '正常' }}
              </span>
            </div>
            <div class="detail-row">
              <label>最后登录:</label>
              <span>{{ formatDate(selectedUser.last_login_at) }}</span>
            </div>
            <div class="detail-row">
              <label>注册时间:</label>
              <span>{{ formatDate(selectedUser.created_at) }}</span>
            </div>
            <div class="detail-row">
              <label>更新时间:</label>
              <span>{{ formatDate(selectedUser.updated_at) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'UserList',
  data() {
    return {
      searchQuery: '',
      genderFilter: '',
      statusFilter: '',
      loading: false,
      error: null,
      toggleLoading: null, // 记录正在切换状态的用户ID
      users: [],
      
      // 分页相关数据
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        pages: 0,
        isFirstPage: true,
        isLastPage: true,
        hasPreviousPage: false,
        hasNextPage: false
      },
      
      // 消息显示
      message: {
        show: false,
        type: '', // 'success' 或 'error'
        text: '',
        timeout: null
      },
      
      // 模态框状态
      showUserModal: false,
      showDetailModal: false,
      isEditMode: false,
      saving: false,
      selectedUser: null,
      
      // 用户表单数据
      userForm: {
        id: null,
        username: '',
        nickname: '',
        email: '',
        phone: '',
        gender: 0,
        status: 1,
        password: '',
        confirmPassword: ''
      }
    };
  },
  computed: {
    // 分页后直接使用users数据，不需要前端过滤
    filteredUsers() {
      return this.users;
    }
  },
  watch: {
    // 监听搜索条件变化
    searchQuery: {
      handler() {
        this.handleSearch();
      },
      deep: true
    },
    // 监听性别筛选变化
    genderFilter: {
      handler() {
        this.handleFilterChange();
      }
    },
    // 监听状态筛选变化
    statusFilter: {
      handler() {
        this.handleFilterChange();
      }
    }
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers(pageNum = this.pagination.pageNum, pageSize = this.pagination.pageSize) {
      this.loading = true;
      this.error = null;
      
      try {
        // 构建查询参数
        const params = {
          pageNum: pageNum,
          pageSize: pageSize
        };
        
        // 添加搜索条件
        if (this.searchQuery && this.searchQuery.trim()) {
          params.keyword = this.searchQuery.trim();
        }
        
        // 添加性别筛选
        if (this.genderFilter !== '') {
          params.gender = this.genderFilter;
        }
        
        // 添加状态筛选
        if (this.statusFilter !== '') {
          params.status = this.statusFilter;
        }
        
        console.log(`正在获取用户列表... 页码: ${pageNum}, 每页数量: ${pageSize}, 查询参数:`, params);
        const response = await axios.get('http://localhost:8080/api/v1/users/list/page', {
          params: params
        });
        console.log('用户列表响应:', response.data);
        
        if (response.data.code === 200 && response.data.ok) {
          const pageInfo = response.data.data;
          this.users = pageInfo.list || [];
          
          // 更新分页信息
          this.pagination = {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            total: pageInfo.total,
            pages: pageInfo.pages,
            isFirstPage: pageInfo.isFirstPage,
            isLastPage: pageInfo.isLastPage,
            hasPreviousPage: pageInfo.hasPreviousPage,
            hasNextPage: pageInfo.hasNextPage
          };
          
          console.log('成功获取用户数据，用户数量:', this.users.length);
          console.log('分页信息:', this.pagination);
          
          // 验证用户数据结构
          if (this.users.length > 0) {
            const firstUser = this.users[0];
            console.log('第一个用户数据结构:', firstUser);
            if (!firstUser.id) {
              console.warn('警告：用户数据缺少ID字段');
            }
          }
        } else {
          console.error('获取用户列表失败，后端返回错误:', response.data);
          this.error = response.data.msg || '获取用户数据失败';
        }
      } catch (error) {
        console.error('获取用户数据失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          this.error = `网络错误：${error.response.data.msg || error.response.statusText}`;
        } else if (error.request) {
          console.error('网络请求错误:', error.request);
          this.error = '网络错误，请检查后端服务是否正常运行';
        } else {
          console.error('请求配置错误:', error.message);
          this.error = '请求配置错误，请联系管理员';
        }
      } finally {
        this.loading = false;
      }
    },
    
    refreshUsers() {
      this.fetchUsers();
    },
    
    // 搜索和筛选处理方法
    handleSearch() {
      // 搜索时重置到第一页
      this.fetchUsers(1, this.pagination.pageSize);
    },
    
    handleFilterChange() {
      // 筛选条件改变时重置到第一页
      this.fetchUsers(1, this.pagination.pageSize);
    },
    
    // 分页相关方法
    changePage(pageNum) {
      if (pageNum >= 1 && pageNum <= this.pagination.pages) {
        this.fetchUsers(pageNum, this.pagination.pageSize);
      }
    },
    
    changePageSize(pageSize) {
      this.pagination.pageSize = pageSize;
      this.fetchUsers(1, pageSize); // 切换每页数量时回到第一页
    },
    
    goToFirstPage() {
      this.changePage(1);
    },
    
    goToLastPage() {
      this.changePage(this.pagination.pages);
    },
    
    goToPreviousPage() {
      if (this.pagination.hasPreviousPage) {
        this.changePage(this.pagination.pageNum - 1);
      }
    },
    
    goToNextPage() {
      if (this.pagination.hasNextPage) {
        this.changePage(this.pagination.pageNum + 1);
      }
    },
    
    getPageNumbers() {
      const current = this.pagination.pageNum;
      const total = this.pagination.pages;
      const delta = 2; // 当前页前后显示的页数
      
      if (total <= 7) {
        // 总页数少于等于7页，显示所有页码
        return Array.from({ length: total }, (_, i) => i + 1);
      }
      
      const range = [];
      const rangeWithDots = [];
      
      // 计算显示范围
      for (let i = Math.max(2, current - delta); i <= Math.min(total - 1, current + delta); i++) {
        range.push(i);
      }
      
      // 添加首页
      if (current - delta > 2) {
        rangeWithDots.push(1, '...');
      } else {
        rangeWithDots.push(1);
      }
      
      // 添加中间页码
      rangeWithDots.push(...range);
      
      // 添加末页
      if (current + delta < total - 1) {
        rangeWithDots.push('...', total);
      } else if (total > 1) {
        rangeWithDots.push(total);
      }
      
      return rangeWithDots;
    },

    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    getGenderText(gender) {
      const genderMap = {
        0: '未知',
        1: '男',
        2: '女'
      };
      return genderMap[gender] || '未知';
    },

    getGenderClass(gender) {
      const classMap = {
        1: 'male',
        2: 'female',
        0: 'unknown'
      };
      return classMap[gender] || 'unknown';
    },

    // 模态框控制方法
    showAddUserModal() {
      this.isEditMode = false;
      this.resetUserForm();
      this.showUserModal = true;
    },

    closeUserModal() {
      this.showUserModal = false;
      this.resetUserForm();
    },

    closeDetailModal() {
      this.showDetailModal = false;
      this.selectedUser = null;
    },

    resetUserForm() {
      this.userForm = {
        id: null,
        username: '',
        nickname: '',
        email: '',
        phone: '',
        gender: 0,
        status: 1,
        password: '',
        confirmPassword: ''
      };
    },
    
    async toggleUserStatus(user) {
      console.log('=== 状态切换方法被调用 ===');
      console.log('用户对象:', user);
      console.log('当前状态:', user ? user.status : 'undefined');
      console.log('用户ID:', user ? user.id : 'undefined');
      
      if (!user || !user.id) {
        console.error('切换状态失败：用户对象或用户ID无效', user);
        alert('操作失败：用户信息无效');
        return;
      }

      this.toggleLoading = user.id;
      console.log('设置加载状态，用户ID:', user.id);
      
      try {
        const newStatus = user.status === 0 ? 1 : 0;
        const statusText = newStatus === 0 ? '禁用' : '启用';
        
        // 添加确认对话框
        if (!confirm(`确定要${statusText}用户 "${user.username}" 吗？`)) {
          this.toggleLoading = null;
          return;
        }
        
        console.log(`正在${statusText}用户:`, user.id, user.username);
        
        // 使用新的后端API - POST /toggle-status
        const params = new URLSearchParams();
        params.append('id', user.id);
        params.append('status', newStatus);
        
        console.log('状态切换请求参数:', { id: user.id, status: newStatus });
        
        const response = await axios.post('http://localhost:8080/api/v1/users/toggle-status', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        console.log('状态切换响应:', response.data);
        
        // 根据新的后端响应格式处理结果
        if (response.data.code === 200 && response.data.ok && response.data.data === true) {
          // 更新本地数据
          const userIndex = this.users.findIndex(u => u.id === user.id);
          if (userIndex !== -1) {
            this.users[userIndex].status = newStatus;
            console.log('本地用户状态已更新');
          }
          
          this.showSuccessMessage(`用户${statusText}成功`);
        } else {
          console.error('状态切换失败，后端返回错误:', response.data);
          this.showErrorMessage(response.data.msg || '操作失败');
        }
        
      } catch (error) {
        console.error('切换用户状态失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          this.showErrorMessage(`操作失败：${error.response.data.msg || error.response.statusText}`);
        } else if (error.request) {
          console.error('网络错误:', error.request);
          this.showErrorMessage('操作失败：网络连接错误');
        } else {
          console.error('请求配置错误:', error.message);
          this.showErrorMessage('操作失败：请求配置错误');
        }
      } finally {
        this.toggleLoading = null;
      }
    },

    // 消息显示方法
    showSuccessMessage(text) {
      this.clearMessage();
      this.message = {
        show: true,
        type: 'success',
        text: text,
        timeout: setTimeout(() => {
          this.clearMessage();
        }, 3000)
      };
    },

    showErrorMessage(text) {
      this.clearMessage();
      this.message = {
        show: true,
        type: 'error',
        text: text,
        timeout: setTimeout(() => {
          this.clearMessage();
        }, 5000)
      };
    },

    clearMessage() {
      if (this.message.timeout) {
        clearTimeout(this.message.timeout);
      }
      this.message = {
        show: false,
        type: '',
        text: '',
        timeout: null
      };
    },

    // 用户操作方法
    editUser(user) {
      this.isEditMode = true;
      this.userForm = {
        id: user.id,
        username: user.username,
        nickname: user.nickname || '',
        email: user.email || '',
        phone: user.phone || '',
        gender: user.gender,
        status: user.status,
        password: '',
        confirmPassword: ''
      };
      this.showUserModal = true;
    },

    async viewUserDetail(user) {
      if (!user || !user.id) {
        console.error('查看详情失败：用户对象或用户ID无效', user);
        alert('查看详情失败：用户信息无效');
        return;
      }

      try {
        console.log('正在获取用户详情:', user.id, user.username);
        const detailUrl = `http://localhost:8080/api/v1/users/${user.id}`;
        console.log('详情请求URL:', detailUrl);
        
        const response = await axios.get(detailUrl);
        console.log('用户详情响应:', response.data);
        
        if (response.data.code === 200 && response.data.ok) {
          this.selectedUser = response.data.data;
          this.showDetailModal = true;
          console.log('用户详情获取成功');
        } else {
          console.error('获取用户详情失败，后端返回错误:', response.data);
          alert(response.data.msg || '获取用户详情失败');
        }
      } catch (error) {
        console.error('获取用户详情失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          alert(`获取详情失败：${error.response.data.msg || error.response.statusText}`);
        } else if (error.request) {
          console.error('网络错误:', error.request);
          alert('获取详情失败：网络连接错误');
        } else {
          console.error('请求配置错误:', error.message);
          alert('获取详情失败：请求配置错误');
        }
      }
    },

    async saveUser() {
      // 表单验证
      if (!this.userForm.username.trim()) {
        alert('请输入用户名');
        return;
      }

      if (!this.isEditMode) {
        if (!this.userForm.password) {
          alert('请输入密码');
          return;
        }
        if (this.userForm.password !== this.userForm.confirmPassword) {
          alert('两次输入的密码不一致');
          return;
        }
      }

      this.saving = true;

      try {
        let response;
        const userData = {
          username: this.userForm.username,
          nickname: this.userForm.nickname,
          email: this.userForm.email,
          phone: this.userForm.phone,
          gender: parseInt(this.userForm.gender),
          status: parseInt(this.userForm.status)
        };

        if (this.isEditMode) {
          // 编辑用户
          if (!this.userForm.id) {
            alert('编辑失败：用户ID无效');
            return;
          }
          userData.id = this.userForm.id;
          console.log('正在更新用户:', userData);
          response = await axios.put('http://localhost:8080/api/v1/users/update', userData);
        } else {
          // 新增用户
          userData.password = this.userForm.password;
          console.log('正在创建用户:', { ...userData, password: '***' });
          response = await axios.post('http://localhost:8080/api/v1/users/add', userData);
        }

        console.log('保存用户响应:', response.data);

        if (response.data.code === 200 && response.data.ok) {
          alert(this.isEditMode ? '用户更新成功' : '用户创建成功');
          this.closeUserModal();
          this.fetchUsers(); // 重新加载用户列表
        } else {
          console.error('保存用户失败，后端返回错误:', response.data);
          alert(response.data.msg || '操作失败');
        }

      } catch (error) {
        console.error('保存用户失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          alert(`操作失败：${error.response.data.msg || error.response.statusText}`);
        } else if (error.request) {
          console.error('网络错误:', error.request);
          alert('操作失败：网络连接错误');
        } else {
          console.error('请求配置错误:', error.message);
          alert('操作失败：请求配置错误');
        }
      } finally {
        this.saving = false;
      }
    },

    async deleteUser(user) {
      // 验证用户对象和ID
      if (!user || !user.id) {
        console.error('删除失败：用户对象或用户ID无效', user);
        alert('删除失败：用户信息无效');
        return;
      }

      if (!confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复！`)) {
        return;
      }

      console.log('正在删除用户:', user.id, user.username);

      try {
        const deleteUrl = `http://localhost:8080/api/v1/users/delete/${user.id}`;
        console.log('删除请求URL:', deleteUrl);
        
        const response = await axios.delete(deleteUrl);
        console.log('删除响应:', response.data);
        
        if (response.data.code === 200 && response.data.ok) {
          alert('用户删除成功');
          this.fetchUsers(); // 重新加载用户列表
        } else {
          console.error('删除失败，后端返回错误:', response.data);
          alert(response.data.msg || '删除失败');
        }

      } catch (error) {
        console.error('删除用户失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          alert(`删除失败：${error.response.data.msg || error.response.statusText}`);
        } else if (error.request) {
          console.error('网络错误:', error.request);
          alert('删除失败：网络连接错误');
        } else {
          console.error('请求配置错误:', error.message);
          alert('删除失败：请求配置错误');
        }
      }
    }
  }
};
</script>

<style scoped>
.user-list {
  padding: 0;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.content-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.left-actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.btn .icon {
  margin-right: 8px;
  font-size: 16px;
}

.filter-group {
  display: flex;
  gap: 12px;
}

.filter-select {
  padding: 8px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.filter-select:focus {
  outline: none;
  border-color: #667eea;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 10px 40px 10px 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.search-box input:focus {
  outline: none;
  border-color: #667eea;
}

.search-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
}

.users-table {
  overflow-x: auto;
}

.users-table table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th,
.users-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

.users-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.users-table td {
  font-size: 14px;
  color: #495057;
}

.users-table tbody tr:hover {
  background: #f8f9fa;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-message {
  text-align: center;
  padding: 40px;
  color: #dc3545;
  background: #f8d7da;
  border-radius: 8px;
  margin: 20px 0;
}

.error-message p {
  margin-bottom: 16px;
}

/* 无数据状态 */
.no-data {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.user-id {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #667eea;
}

.username {
  font-weight: 600;
  color: #2c3e50;
}

.integral {
  font-weight: 600;
  color: #28a745;
}

/* 性别标签 */
.gender {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.gender.male {
  background: #cce5ff;
  color: #0066cc;
}

.gender.female {
  background: #ffe6f0;
  color: #cc0066;
}

.gender.unknown {
  background-color: #f6f6f6;
  color: #999;
}

/* 操作按钮 */
.actions {
  display: flex;
  gap: 8px;
}

.btn-edit, .btn-view, .btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-edit {
  background: #17a2b8;
  color: white;
}

.btn-edit:hover {
  background: #138496;
}

.btn-view {
  background: #6c757d;
  color: white;
}

.btn-view:hover {
  background: #5a6268;
}

.btn-delete {
  background: #dc3545;
  color: white;
}

.btn-delete:hover {
  background: #c82333;
}

/* 状态显示 */
.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status.active {
  background-color: #e8f5e8;
  color: #52c41a;
}

.status.disabled {
  background-color: #fff2f0;
  color: #ff4d4f;
}

/* 禁用行样式 */
.disabled-row {
  background-color: #f5f5f5;
  opacity: 0.7;
}

.disabled-row td {
  color: #999;
}

/* 启用/禁用按钮 */
.btn-toggle {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.btn-enable {
  background-color: #52c41a;
  color: white;
}

.btn-enable:hover {
  background-color: #389e0d;
}

.btn-disable {
  background-color: #ff4d4f;
  color: white;
}

.btn-disable:hover {
  background-color: #d9363e;
}

.btn-toggle:disabled {
  background-color: #d9d9d9;
  color: #999;
  cursor: not-allowed;
}

/* 禁用状态下的按钮 */
.actions button:disabled {
  background-color: #f5f5f5;
  color: #d9d9d9;
  cursor: not-allowed;
  border-color: #d9d9d9;
}

.actions button:disabled:hover {
  background-color: #f5f5f5;
  color: #d9d9d9;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #dc3545;
}

.modal-body {
  padding: 24px;
}

/* 表单样式 */
.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input:disabled {
  background-color: #f8f9fa;
  color: #6c757d;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

/* 详情页面样式 */
.detail-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f8f9fa;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-row label {
  font-weight: 500;
  color: #495057;
  width: 120px;
  flex-shrink: 0;
}

.detail-row span {
  color: #6c757d;
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .left-actions {
    justify-content: center;
  }
  
  .filter-group {
    justify-content: center;
  }
  
  .search-box {
    width: 100%;
  }
  
  .form-row {
    flex-direction: column;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .users-table {
    font-size: 12px;
  }
  
  .users-table th,
  .users-table td {
    padding: 8px 4px;
  }
  
  .actions {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .actions button {
    font-size: 11px;
    padding: 4px 8px;
  }
}

/* 消息提示样式 */
.message-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2000;
  min-width: 300px;
  max-width: 500px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideInRight 0.3s ease, fadeOut 0.3s ease 4.7s forwards;
  cursor: pointer;
  
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateX(0);
  }
  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

.message-toast.success {
  background: linear-gradient(135deg, rgba(46, 204, 113, 0.95) 0%, rgba(39, 174, 96, 0.95) 100%);
  border-left: 4px solid #27ae60;
}

.message-toast.error {
  background: linear-gradient(135deg, rgba(231, 76, 60, 0.95) 0%, rgba(192, 57, 43, 0.95) 100%);
  border-left: 4px solid #c0392b;
}

.message-content {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  color: white;
  position: relative;
}

.message-icon {
  font-size: 18px;
  font-weight: bold;
  margin-right: 12px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
}

.message-text {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
}

.message-close {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
  margin-left: 12px;
  flex-shrink: 0;
}

.message-close:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 响应式消息提示 */
@media (max-width: 768px) {
  .message-toast {
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
    max-width: none;
  }
  
  .message-content {
    padding: 12px 16px;
  }
  
  .message-text {
    font-size: 13px;
  }
}

/* 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  padding: 20px 0;
  border-top: 1px solid #e9ecef;
  background: white;
  border-radius: 0 0 12px 12px;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #6c757d;
  font-size: 14px;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-selector label {
  font-weight: 500;
  color: #495057;
}

.page-size-selector select {
  padding: 6px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.page-size-selector select:focus {
  outline: none;
  border-color: #667eea;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-numbers {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0 12px;
}

.page-btn {
  min-width: 36px;
  height: 36px;
  border: 2px solid #e9ecef;
  background: white;
  color: #495057;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  user-select: none;
}

.page-btn:hover:not(:disabled) {
  border-color: #667eea;
  color: #667eea;
  background: #f8f9ff;
}

.page-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.page-btn:disabled {
  background: #f8f9fa;
  color: #d9d9d9;
  border-color: #e9ecef;
  cursor: not-allowed;
}

.page-btn:disabled:hover {
  background: #f8f9fa;
  color: #d9d9d9;
  border-color: #e9ecef;
}

/* 响应式分页 */
@media (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .pagination-info {
    justify-content: center;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .page-numbers {
    margin: 0 8px;
  }
  
  .page-btn {
    min-width: 32px;
    height: 32px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .pagination-info {
    font-size: 12px;
  }
  
  .page-size-selector {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
  
  .page-btn {
    min-width: 28px;
    height: 28px;
    font-size: 12px;
  }
  
  .page-numbers {
    gap: 2px;
  }
}
</style>